﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CSharpWin;
using FirstFloor.ModernUI.Windows.Controls;
using YanMsg.APCode;
using System.Linq;
using CSharpWin_JD.CaptureImage;
using agsXMPP.protocol.client;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Data;

namespace YanMsg.View
{
    /// <summary>
    /// Chat.xaml 的交互逻辑
    /// </summary>
    public partial class GroupChat : ModernWindow
    {

        public string Key = null;

        public static YanChat_Group groupinfo = null;
        public static ObservableCollection<vw_Yan_Chat_user> ListGroupUsers = null;
        /// <summary>
        /// 消息来时闪烁任务栏
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="WinkIf"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern bool FlashWindow(IntPtr hWnd, bool WinkIf);

        /// <summary>
        ///
        /// </summary>
        /// <param name="userName">当前用昵称</param>
        /// <param name="netStream">发送和接受信息的网络流</param>
        public GroupChat(string Groupid)
        {
            groupinfo = UserData.ListGroup.SingleOrDefault(D => D.ID.ToString() == Groupid);
            InitializeComponent();
            this.Style = (Style)App.Current.Resources["EmptyWindow"];
            this.Key = Groupid;
            List<string> ListUser = new YanChatHelp().GetGroupUsers(Groupid);

            ListGroupUsers = UserData.ListPeople.Where(d => ListUser.Contains(d.UserName)).ToObservableCollection();
            GroupUsers.ItemsSource = ListGroupUsers;
            this.ViewMessgeBox.Document.Blocks.Clear();
            DataTable ListMsg = ChatHelp.GetGroupChatHis(int.Parse(Groupid), "", 10);

            for (int i = 0; i < ListMsg.Rows.Count; i++)
            {
                string msgConTent = ZipHelper.GZipDecompressString(ListMsg.Rows[i]["GMsgContent"].ToString());

                //将信息加载到临时RichTextBox
                System.Windows.Controls.RichTextBox RTemp = new System.Windows.Controls.RichTextBox();
                ChatManger.LoadFromRTF(RTemp, msgConTent);

                //添加信息头
                string strMSTitle = ChatManger.GetUserName(ListMsg.Rows[i]["CRUser"].ToString()) + "  " + DateTime.Parse(ListMsg.Rows[i]["CRDate"].ToString()).ToString("yyyy-MM-dd HH:mm");
                TextBlock TB = new TextBlock(new Bold(new Run(strMSTitle)));
                if (ListMsg.Rows[i]["CRUser"].ToString() == UserData.UserNumber)
                {
                    TB.Foreground = new SolidColorBrush(Colors.Blue);
                }
                BlockUIContainer BU = new BlockUIContainer(TB);

                this.ViewMessgeBox.Document.Blocks.Add(BU);
                //添加信息内容
                for (int m = RTemp.Document.Blocks.Count - 1; m >= 0; m--)
                {
                    var q = RTemp.Document.Blocks.ElementAt(m);
                    this.ViewMessgeBox.Document.Blocks.Add(q);
                }
            }
            this.ViewMessgeBox.ScrollToEnd();

        }


        /// <summary>
        /// 关闭后动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WindowTalking_Closed(object sender, EventArgs e)
        {
            UserData.DictionaryGroupChat.Remove(this.Key);
        }
        private void CloseButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 消息来时闪烁任务栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ViewMessgeBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
            {
                //得到当前窗体的句柄
                WindowInteropHelper Helper = new WindowInteropHelper(this);
                IntPtr ptr = Helper.Handle;
                FlashWindow(ptr, true);//闪烁任务栏
            }
        }





        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SendMessageButton_Click(object sender, RoutedEventArgs e)
        {
            SendMsg();
        }

        private void Login_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && e.Key == System.Windows.Input.Key.Enter)
            {
                SendMsg();
            }

        }

        private void SendMsg()
        {
            TextRange msgBoxContent = new TextRange(this.MyMessageBox.Document.ContentStart, this.MyMessageBox.Document.ContentEnd);
            if (!msgBoxContent.IsEmpty)
            {
                //所有的讨论组信息均发给讨论组Jid
                Message msg = new Message();
                msg.Type = MessageType.groupchat;
                msg.From = UserData.UserNumber.TOJid();
                msg.To = groupinfo.ID.ToString().TOJid();
                msg.Body = ZipHelper.GZipCompressString(ChatManger.toRtf(this.MyMessageBox));


                Login.connection.Send(msg);
                //存到本地
                // ChatHelp.InsertChat(msg.From.User, msg.To.User, msg.Body, (int)MessageType.groupchat);



                this.ViewMessgeBox.ScrollToEnd();
                this.MyMessageBox.Document.Blocks.Clear();
            }
        }

        //聊天记录
        private void imgChatHistory_MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            GroupChatHistory history = new GroupChatHistory(groupinfo.ID);
            history.Topmost = true;
            history.Show();
        }

        //截图
        private void imgCut_MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            this.Hide();
            CaptureImageTool capture = new CaptureImageTool();
            //capture.SelectCursor = new Cursor(Properties.Resources.Arrow_M.Handle);
            if (capture.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                System.Drawing.Image image = capture.Image;
                Clipboard.SetDataObject(image);
                this.MyMessageBox.Paste();
            }
            this.Show();
        }





    }
}